package com.example.dayu521.gateway.conf;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
@Profile({"dev","prototype"})
public class RedisConf {
    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    private static ObjectMapper objectMapper;

    static {
        ObjectMapper b = new ObjectMapper();
        //默认转long类型
        b.enable(DeserializationFeature.USE_LONG_FOR_INTS);

        //https://zhuanlan.zhihu.com/p/148753594
//        b.activateDefaultTyping(BasicPolymorphicTypeValidator.builder().allowIfBaseType(Object.class).build()
//                , ObjectMapper.DefaultTyping.NON_FINAL
//                , JsonTypeInfo.As.WRAPPER_ARRAY);
        objectMapper = b;

    }

    @Bean("redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
//        //GenericJackson2JsonRedisSerializer
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(getObjectMapper(), Object.class);
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(serializer);
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(serializer);
        return template;
    }
}
